package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by zjx on 2018
 */

public class UsermodifyPhoneActivity extends AppCompatActivity {
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.phone_title)
    TextView phoneTitle;
    @BindView(R.id.iphone_tv)
    TextView iphoneTv;
    @BindView(R.id.user_iv)
    ImageView userIv;
    @BindView(R.id.getvalidate_bt)
    Button getvalidateBt;
    @BindView(R.id.edit_iphone)
    EditText editIphone;
    @BindView(R.id.accout_rl)
    RelativeLayout accoutRl;
    @BindView(R.id.validate_iv)
    ImageView validateIv;
    @BindView(R.id.edit_yanzhen)
    EditText editYanzhen;
    @BindView(R.id.validate_rl)
    RelativeLayout validateRl;
    @BindView(R.id.successbt)
    RelativeLayout successbt;
    private String iphonetv;
    private boolean isZuce = false;
    public Dialog loadingdialog = null;
    private EventHandler eventHandler;
    private YanzhenThread yanzhenThread;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usermodifyphone);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        locationUserServer();
        webUserServer();
    }

    public void initComponent() {
        this.loadingdialog = new Dialog(this);
        this.loadingdialog.setContentView(R.layout.dialog_loading);
        this.loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        this.loadingdialog.setCanceledOnTouchOutside(false);
        this.yanzhenThread = new YanzhenThread(1000L);
        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, final Object data) {
                super.afterEvent(event, result, data);
                switch (event) {
                    case SMSSDK.EVENT_GET_VERIFICATION_CODE:
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "验证码已发送,请稍等..", Toast.LENGTH_SHORT).show();

                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String str = ((Throwable) data).getMessage();
                                    try {
                                        JSONObject jb = new JSONObject(str);
                                        Toast.makeText(getApplicationContext(), jb.getString("detail") + "", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });
                        }
                        break;

                    case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE:
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    isZuce = true;
                                    modifyIphone(editIphone.getText().toString().trim());
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String str = ((Throwable) data).getMessage();
                                    try {
                                        JSONObject jb = new JSONObject(str);
                                        Toast.makeText(getApplicationContext(), jb.getString("detail"), Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }
                        break;
                }

            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }

    @OnClick(value = {R.id.backbt,R.id.successbt,R.id.getvalidate_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.successbt:
                if (TextUtils.isEmpty(this.iphonetv))
                {
                    Toast.makeText(getApplicationContext(), "没有发送验证码?", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(this.editIphone.getText().toString().trim()))
                {
                    Toast.makeText(getApplicationContext(), "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (this.isZuce)
                {
                    modifyIphone(this.editIphone.getText().toString().trim());
                    return;
                }
                if (TextUtils.isEmpty(this.editYanzhen.getText().toString().trim()))
                {
                    Toast.makeText(getApplicationContext(), "验证码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                    SMSSDK.submitVerificationCode("86", this.iphonetv, this.editYanzhen.getText().toString().trim());


                break;
            case R.id.getvalidate_bt:
                if (TextUtils.isEmpty(this.editIphone.getText().toString().trim()))
                {
                    Toast.makeText(getApplicationContext(), "没有填写手机号码?", 0).show();
                    return;
                }
                this.yanzhenThread = new YanzhenThread(1000L);
                this.yanzhenThread.start();
                this.iphonetv = this.editIphone.getText().toString().trim();
                SMSSDK.getVerificationCode("86", this.iphonetv);
                break;

        }
    }

  public void modifyIphone(String userIphone){
        List<User> userList=Xutils.queryAll(getApplication(),User.class);
          if(userList==null||userList.size()==0){
              return;
          }
      Map<String,String> localHashMap = new HashMap();
      localHashMap.put("userId", userList.get(0).getUserId() + "");
      localHashMap.put("userIphone", userIphone);
      UsermodifyPhoneActivity.this.loadingdialog.show();
      Xutils.POST(HttpUrl.usermodifyiphone, localHashMap, new Callback.CommonCallback<String>() {
          @Override
          public void onSuccess(String result) {
              UsermodifyPhoneActivity.this.loadingdialog.dismiss();
              try {
                  JSONObject jsonObject=new JSONObject(result);
                  Toast.makeText(getApplicationContext(),""+jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
               switch (jsonObject.getInt("state")){
                   case HttpCode.SUCCESS:
                       finish();
                       break;
               }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          }

          @Override
          public void onError(Throwable ex, boolean isOnCallback) {
              UsermodifyPhoneActivity.this.loadingdialog.dismiss();
              Toast.makeText(UsermodifyPhoneActivity.this.getApplicationContext(), "网络有误", Toast.LENGTH_SHORT).show();

          }

          @Override
          public void onCancelled(CancelledException cex) {

          }

          @Override
          public void onFinished() {

          }
      });
  }



    private class YanzhenThread extends Thread {
        private boolean isLoading = true;
        private long sleep = 1000;
        private int time = 60;

        public YanzhenThread(long sleep) {
            this.sleep = sleep;
        }

        @Override
        public void run() {
            super.run();
            while (time != 0 && isLoading == true) {
                SystemClock.sleep(sleep);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getvalidateBt != null) {
                            getvalidateBt.setClickable(false);
                            getvalidateBt.setTextColor(getResources().getColor(R.color.gray));
                            getvalidateBt.setText("重新发送还有" + time + "秒");
                        }

                    }
                });
                time--;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (getvalidateBt != null) {
                        getvalidateBt.setText("获取验证码");
                        getvalidateBt.setTextColor(getResources().getColor(R.color.default_theme));
                        getvalidateBt.setClickable(true);
                    }
                }
            });
            time = 60;
        }
    }



    protected void onDestroy()
    {
        super.onDestroy();
        try
        {if(yanzhenThread!=null){
            this.yanzhenThread.join();
            this.yanzhenThread = null;
        }

            if (this.eventHandler != null) {
                SMSSDK.unregisterEventHandler(this.eventHandler);
            }
            return;
        }
        catch (InterruptedException localInterruptedException)
        {
            for (;;)
            {
                localInterruptedException.printStackTrace();
            }
        }
    }

    public void webUserServer() {
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId", userList.get(0).getUserId() + "");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserDomain userDomain = gson.fromJson(result, UserDomain.class);
                switch (userDomain.getState()) {
                    case HttpCode.SUCCESS:
                        User user = userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(), user);
                        locationUserServer();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void locationUserServer()
    {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if(userList==null||userList.size()==0){
            return;
        }
        User user=userList.get(0);
        if(!TextUtils.isEmpty(user.getUserIphone())){
            iphoneTv.setText(""+user.getUserIphone().substring(0,3)+"*******");
        }else{
            iphoneTv.setText("");
        }


    }
}
